/*
 * @Author: ChunLai
 * @Date: 2023-07-26 10:33:07
 * @LastEditTime: 2025-09-17 09:39:20
 * @Description:
 * @FilePath: \02.bldinsure\src\store\modules\insert.js
 */
import consts from "@/config/const.js";
import { userAge } from "@/methods/globals";
import { dateToString } from "@/methods/date.js";
const userModel = {
  isSame: "0",
  syrToInsNo: 0, // 受益人关联被保人序号
  relationToInsured: "",
  relationToInsuredName: "",
  name: "",
  idType: "",
  idName: "",
  idNum: "",
  validDate: "",
  validDateEnd: "",
  occupationCode: "",
  occupationCodeName: "",
  occupationClass: "",
  sex: "",
  birthDate: "",
  height: "",
  weight: "",
  phone: "",
  areaName: "",
  permanentAddress: "",
  province: "",
  city: "",
  county: "",
  nationality: "",
  nationalityName: "",
  bnfType: "1",
  bnfTypeName: "身故受益人",
  addressTypeNo: "2",
  addressTypeNoName: "同投保人",
  beneficialOrder: 1,
  beneficialRate: "",
  type: 1,
};
// 公共必备字段
const bbrModel = {
  name: "",
  idType: "",
  idName: "",
  idNum: "",
  validDate: "",
  validDateEnd: "",
  sex: "",
  birthDate: "",
  risks: [],
  bnfCategory: "", //2
  bnfs: [],
};

const state = {
  typeFlag: "", // 险种标识（1：团险）
  comCode: "", // "机构编码",
  workNum: "", // "岗位号",
  orderNum: "", // "订单号",
  mainRiskCode: "", // "主险编码",
  // varietyInfo.msProduct.productNo
  proUniqueId: "", // （产品唯一ID：后端自生成key）
  // 链接配置获取：goodsNo
  proBldIdNo: "", // （一个110176MS2，可对应多个）
  bldUserId: "", //用户ID
  compEngName: "",
  msChannel: "", // 新增字段(xdd)
  isNeedDouble: "0", // 是否需要双录 0不需要，1需要，2需要双录,且已推送
  contractNum: "",
  underwriteFlag: "", // 核保状态
  insureFlag: "", // 保单状态
  insureMsg: "", // 保单提示
  forbidAlter: false, // 禁止修改信息
  channelType: "1", // 3短险打款后继续投保（试算因子不可改）
  applicant: {
    age: "18",
    IMPARTCOUNT: 1,
    IMPARTS: "",
    name: "",
    idType: "",
    idName: "",
    idNum: "",
    validDate: "",
    validDateEnd: "",
    sex: "1",
    birthDate: "",
    nationality: "",
    nationalityName: "",
    phone: "",
    validCode: "",
    email: "",
    occupationCode: "",
    occupationCodeName: "",
    occupationClass: "",
    socialInsuFlag: "Y",
    maritalStatus: "",
    maritalStatusName: "",
    degree: "",
    areaName: "",
    permanentAddress: "",
    province: "",
    postalProvince: "",
    homeProvince: "",
    height: "",
    weight: "",
    city: "",
    county: "",
    zipCode: "",
    crsIdTypeName: "",
    printPolType: "",
    partTimeJob: "",
    position: "",
  },
  payInfo: {
    transrNo: "", // "交易串号",
    hospitalCode: "",
    hospitalCodeName: "",
    printPolType: "E", // "获取保单类型，E 电子保单，P 纸质保单",
    totalPrem: "", //"总保费",
    payMode: "R",
    bankCode: "", //"银行编码",
    bankName: "", //"银行名称",
    bankAccName: "", //"持卡人户名",
    bankAccNo: "", //"银行卡号",
    firBankMobile: "", // "预留手机号",
    bankProvince: "", // "开户行省份",
    bankCity: "", //"开户行市",
    bankCounty: "", //"开户行区县",
    bankArea: "", //"开户行地区（省+市+区）",
    bankCardType: "", // "银行卡类型",
    autoPayFlag: "0", // "自动垫交标志",
    aliveGetMode: "N", //"生存金领取授权，Y授权，N不授权",
    bnfBankAccName: "", //"生存受益人授权账号户名",
    bnfBankCode: "", //"生存受益人授权银行编号",
    bnfBankAccNo: "", // "生存受益人授权银行卡号"
    expayMode: "4",
    addRiskCode: "", // 复星智能核保豁免险编码
    // 生效日期
    effectiveDate: "",
    expiryDate: "",
  },
  recall: "0", // 防止reBackRiskApiInfos方法无效调用
  // 设备信息
  terminalMsg: {
    terminalMac: "",
    terminalIp: "",
    terminalType: "1", // 0 PC 1 YD
  },
  bbrMultList: [], //多被保人
  bbrTarget: {},
  /**续保新模块*/
  renewalInfo: {
    renewFlag: "",
    bankAccName: "",
    bankAccNo: "",
    firBankMobile: "",
  },
  /**标体新模块*/
  targetInfo: {},
};
const getters = {
  typeFlag: (state) => state.typeFlag,
  workNum: (state) => state.workNum,
  orderNum: (state) => state.orderNum,
  msChannel: (state) => state.msChannel,
  mainRiskCode: (state) => state.mainRiskCode,
  compEngName: (state) => state.compEngName,
  proUniqueId: (state) => state.proUniqueId,
  proBldIdNo: (state) => state.proBldIdNo,
  forbidAlter: (state) => state.forbidAlter,
  underwriteFlag: (state) => state.underwriteFlag,
  terminalMsg: (state) => state.terminalMsg,
  recall: (state) => state.recall,
  bldUserId: (state) => state.bldUserId,
  insureFlag: (state) => state.insureFlag,
  insureMsg: (state) => state.insureMsg,
  isNeedDouble: (state) => state.isNeedDouble,
  contractNum: (state) => state.contractNum,
  channelType: (state) => state.channelType,
  applicant: (state) => state.applicant,
  tbrPrvinCapital: (state) => {
    return (
      state.applicant.province ||
      state.applicant.postalProvince ||
      state.applicant.homeProvince ||
      ""
    );
  },
  bbrMultList: (state) => state.bbrMultList,
  payInfo: (state) => state.payInfo,
  renewalInfo: (state) => state.renewalInfo,
  totalPrem: (state) => state.payInfo.totalPrem,
  iptStateCfgs: (state, getters, rootState) => {
    let objs = JSON.parse(JSON.stringify(rootState.infoReg.inputReg));
    return objs;
  },
  appnt: (state, getters, rootState) => {
    let objs = JSON.parse(JSON.stringify(getters.iptStateCfgs.applicant));
    for (const key in objs) {
      objs[key] = state.applicant[key];
    }
    if (state.applicant.age != void 0) {
      objs.age = state.applicant.age;
    }
    return objs;
  },
  // 多被保人接口数据
  apiBbrMult: (state, getters) => {
    const objs = JSON.parse(JSON.stringify(getters.iptStateCfgs.insured));
    let list = [];
    const len = state.bbrMultList.length;
    for (let h = 0; h < len; h++) {
      const item = state.bbrMultList[h];
      let tar = JSON.parse(JSON.stringify(objs));
      for (const key in tar) {
        tar[key] = item[key];
      }
      if (item.age != void 0) {
        tar.age = item.age;
      }
      if (item.bnfCategory != void 0) {
        tar.bnfCategory = item.bnfCategory || "2";
      }
      if (item.bnfs != void 0) {
        tar.bnfs = [];
        if (item.bnfs.length > 0) {
          let obj3s = JSON.parse(
            JSON.stringify(getters.iptStateCfgs.benefitModel)
          );
          let arr3 = [];
          const len = item.bnfs.length;
          for (let t = 0; t < len; t++) {
            const ele = item.bnfs[t];
            let t3 = JSON.parse(JSON.stringify(obj3s));
            for (const key in t3) {
              t3[key] = ele[key];
            }
            if (ele.age != void 0) {
              t3.age = ele.age;
            }
            arr3.push(t3);
          }
          tar.bnfs = arr3;
        }
      }
      list.push(tar);
    }
    // 空白同投保人赋值
    const len2 = list.length;
    const tbrApi = JSON.parse(JSON.stringify(getters.appnt));
    for (let i = 0; i < len2; i++) {
      const tar2 = list[i];
      if (tar2.relationToAppnt == "4") {
        for (const key in tar2) {
          if (tbrApi.hasOwnProperty(key) && !consts.empty(tbrApi[key])) {
            tar2[key] = tbrApi[key];
          }
        }
      }
    }
    return list;
  },
  cont: (state, getters, rootState) => {
    let objs = JSON.parse(JSON.stringify(getters.iptStateCfgs.payInfo));
    for (const key in objs) {
      objs[key] = state.payInfo[key];
    }
    objs.bankAccName = state.applicant.name;
    /**续保字段拼接*/
    let xbApiReg = JSON.parse(JSON.stringify(rootState.page.renewal));
    if (Object.keys(xbApiReg).length > 0) {
      for (const key in xbApiReg) {
        xbApiReg[key] = state.renewalInfo[key];
      }
      Object.assign(objs, xbApiReg);
    }
    return objs;
  },
};
const mutations = {
  UPDATE_APPLICANT(state, payload) {
    Object.assign(state.applicant, payload);
  },
  UPDATE_APPNI_CFG(state, payload) {
    state.applicant = Object.assign({}, payload, state.applicant);
  },
  UPDATE_PAYINFO(state, payload) {
    Object.assign(state.payInfo, payload);
  },
  UPDATE_RENEWAL_INFO(state, payload) {
    Object.assign(state.renewalInfo, payload);
  },
  UPDATE_TERMINAL(state, payload) {
    Object.assign(state.terminalMsg, payload);
  },
  SET_ORDER_NUM(state, payload) {
    state.orderNum = payload;
  },
  SET_WORK_NUM(state, payload) {
    state.workNum = payload;
  },
  SET_MAIN_RISK_CODE(state, payload) {
    state.mainRiskCode = payload;
  },
  SET_CONTRACT_NUM(state, payload) {
    state.contractNum = payload;
  },
  SET_COMP_ENG(state, payload) {
    state.compEngName = payload;
  },
  SET_UNIQUE_ID(state, payload) {
    state.proUniqueId = payload;
  },
  SET_BLD_ID(state, payload) {
    state.proBldIdNo = payload;
  },
  SET_UNDERWRITE_FLAG(state, payload) {
    state.underwriteFlag = payload.code || "";
  },
  SET_INSURE_FLAG(state, payload) {
    state.insureFlag = payload.code || "";
    state.insureMsg = payload.msg || "";
  },
  SET_FORBID_ALTER(state, payload) {
    state.forbidAlter = payload;
  },
  SET_RECALL(state, payload) {
    state.recall = payload;
  },
  SET_BLD_UID(state, payload) {
    state.bldUserId = payload;
  },
  SET_TYPE_FLAG(state, payload) {
    state.typeFlag = payload;
  },
  SET_DOUBLE_VIDEO(state, payload) {
    state.isNeedDouble = payload;
  },
  SET_MS_CHANNEL(state, payload) {
    state.msChannel = payload;
  },
  /* === 多被保人 === */
  SET_MULT_BBR_TRG(state, payload) {
    Object.assign(state.bbrTarget, payload);
  },
  // 添加
  ADD_MULT_BBR(state, payload) {
    state.bbrMultList.push(payload);
  },
  // 更新
  UPDATE_MULT_BBR(state, payload) {
    Object.assign(state.bbrMultList[payload.index], payload.data);
    state.bbrMultList.splice(1, 0);
  },
  // 删除
  DELETE_MULT_BBR(state, index) {
    state.bbrMultList.splice(index, 1);
  },
  SET_MULT_BBR(state, payload) {
    state.bbrMultList = [];
    if (payload && payload.length > 0) {
      payload.forEach((element, index) => {
        state.bbrMultList.push(JSON.parse(JSON.stringify(state.bbrTarget)));
        Object.assign(state.bbrMultList[index], element);
      });
    }
  },
  /* === 多被保人-END === */
  SET_CHANL_TYPE(state, payload) {
    state.channelType = payload;
  },
};
const actions = {
  initNewBbr({ commit, state, dispatch }) {
    if (state.bbrMultList.length == 0) {
      dispatch("addNewBbr", "init");
    }
  },
  addNewBbr({ commit, state, rootGetters }, status = "") {
    const bbrMax = rootGetters["infoReg/bbBirthMax"],
      bbrMinNum = rootGetters["page/bbrMinNum"],
      birthStr = dateToString(bbrMax);
    let item = {};
    const bbrCfg = JSON.parse(JSON.stringify(state.bbrTarget)),
      obj2 = JSON.parse(JSON.stringify(bbrModel));
    item = Object.assign({}, obj2, bbrCfg);
    item.birthDate = birthStr;
    item.age = userAge(birthStr);
    item.sex = "1";
    item.socialInsuFlag = "Y";
    item.relationToAppnt = "";
    item.relationToAppntName = "";
    if (state.bbrMultList.length > 0) {
      item.relationToMain = "";
      item.relationToMainName = "";
    } else {
      item.relationToMain = "4";
      item.relationToMainName = "本人";
    }
    if (status === "init" && bbrMinNum === 0) {
      item.relationToAppnt = "4";
      item.relationToAppntName = "本人";
    }
    item.bnfCategory = "2"; //不指定受益人
    item.idType = "0";
    item.idName = "身份证";
    commit("ADD_MULT_BBR", item);
  },
  delBbrItem({ commit, state }, index) {
    // 删除被保人
    commit("DELETE_MULT_BBR", index);
  },
  addNewSyr({ commit, rootGetters, state }, bindex) {
    const sryObj = rootGetters["infoReg/syrApiReg"],
      syrCfg = JSON.parse(JSON.stringify(sryObj)),
      obj2 = JSON.parse(JSON.stringify(userModel));
    let item = Object.assign({}, obj2, syrCfg);
    item.syrToInsNo = bindex;
    // 被保人
    let bbrItem = JSON.parse(JSON.stringify(state.bbrMultList[bindex]));
    bbrItem.bnfs.push(item);
    commit("UPDATE_MULT_BBR", {
      index: bindex,
      data: bbrItem,
    });
  },
  delSyrItem({ commit, state }, payload) {
    let bbrItem = JSON.parse(JSON.stringify(state.bbrMultList[payload.bindex]));
    bbrItem.bnfs.splice(payload.pindex, 1);
    commit("UPDATE_MULT_BBR", {
      index: payload.bindex,
      data: bbrItem,
    });
  },
  updateSyrItem({ commit, state }, payload) {
    // console.log("updateSyrItem", payload);
    let bbrItem = JSON.parse(JSON.stringify(state.bbrMultList[payload.bindex]));
    bbrItem.bnfs[payload.pindex] = Object.assign(
      {},
      bbrItem.bnfs[payload.pindex],
      payload.data
    );
    commit("UPDATE_MULT_BBR", {
      index: payload.bindex,
      data: bbrItem,
    });
  },
  apiRebackBbrSyr({ commit }, data = []) {
    const len = data.length;
    if (len > 0) {
      for (let b = 0; b < len; b++) {
        const item = data[b];
        if (item.bnfs && item.bnfs.length > 0) {
          const len2 = item.bnfs.length;
          for (let s = 0; s < len2; s++) {
            const ele = item.bnfs[s];
            ele.syrToInsNo = `${b}`;
          }
        }
      }
      commit("SET_MULT_BBR", data);
    }
  },
  validateInsureRule({ state, rootGetters }) {
    return new Promise((reslove, reject) => {
      const bbrlen = state.bbrMultList.length,
        mainInsu = rootGetters["risks/mainInsu"][0];
      if (state.mainRiskCode == "110150") {
        if (bbrlen == 2) {
          const sex1 = state.bbrMultList[0].sex,
            sex2 = state.bbrMultList[1].sex,
            age1 = state.bbrMultList[0].age,
            age2 = state.bbrMultList[1].age;
          if (sex1 == sex2 && age1 < age2) {
            reject(
              "对于双人型保单，如果两个被保险人性别相同，则被保险人1的年龄必须大于等于被保险人2"
            );
            return;
          } else if (sex1 != sex2 && sex1 == "1") {
            reject("如果两个被保险人性别不同，则被保险人1必须是男性");
            return;
          }
        }
      }

      if (state.mainRiskCode == "110161") {
        const mAmnt = mainInsu.amnt;
        if (mainInsu.idcardAreaLimitAmnt) {
          const bbrArea = state.bbrMultList[0].provinceName,
            limits = mainInsu.idcardAreaLimitAmnt,
            chkObj = limits.find((e) => {
              const list = e.area.split("、"),
                obj2 = list.find((s) => bbrArea.indexOf(s) !== -1);
              if (obj2) {
                return e;
              }
            });
          if (chkObj) {
            if (chkObj.maxAmnt && mAmnt > chkObj.maxAmnt) {
              reject(`${chkObj.err}；请修改`);
              return;
            }
          } else {
            if (mAmnt > 700000) {
              reject(
                `B类地区：除A类、C类外的其他地区，累计重疾基本保额上限70万元；请修改`
              );
              return;
            }
          }
        }
      }
      if (state.mainRiskCode == "110176") {
        if (bbrlen > 1 && mainInsu.planCode === "1") {
          reject(`${mainInsu.productName}：选计划1，不能添加附加被保人。`);
          return;
        }
      }
      reslove("");
    });
  },
  apiRebackXuBao({ state, commit, rootState }, data = {}) {
    let xbApiReg = JSON.parse(JSON.stringify(rootState.page.renewal));
    if (Object.keys(xbApiReg).length > 0) {
      for (const key in xbApiReg) {
        xbApiReg[key] = data[key] || "";
      }
      commit("UPDATE_RENEWAL_INFO", xbApiReg);
    }
  },
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};
